<?php


namespace App\Services\Game;


use App\DTOS\Admin\RoleUpgradeDTO;
use App\DTOS\Admin\UserMemberDTO;
use App\Exceptions\ServiceException;
use App\Models\Game\RoleUpgrade;

class RoleUpgradeService
{
    private UserRoleService $userRoleService;
    private UserMemberService $userMemberService;

    /**
     * RoleUpgradeService constructor.
     * @param UserRoleService $userRoleService
     * @param UserMemberService $userMemberService
     */
    public function __construct(UserRoleService $userRoleService, UserMemberService $userMemberService)
    {
        $this->userRoleService = $userRoleService;
        $this->userMemberService = $userMemberService;
    }

    /**
     * @param RoleUpgradeDTO $DTO
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function paginate(RoleUpgradeDTO $DTO){
        $model = RoleUpgrade::query();
        $page = $DTO->getPage();
        $pageSize = $DTO->getLimit();
        global $gameArea;
        $gameArea = $DTO->getGameArea();

        $createDateBegin = $DTO->getCreateDateBegin();
        $createDateEnd = $DTO->getCreateDateEnd();
        $memberName = $DTO->getMemberName();
        $roleId = $DTO->getRoleId();
        $nick = $DTO->getNick();
        if ($createDateBegin) {
            $model->where('logTime','>=',strtotime($createDateBegin));
        }
        if ($createDateEnd) {
            $model->where('logTime','<=',strtotime($createDateEnd));
        }
        if ($memberName){
            $userMemberPaginate = $this->userMemberService->paginate(new UserMemberDTO(['username'=>$memberName]));
            $searchMembers = $userMemberPaginate->items();
            $searchMemIds = collect($searchMembers)->pluck('id')->unique()->toArray();
            if (empty($searchMemIds)){
                throw new ServiceException("此账号不存在");
            }
            $model->whereIn('memId',$searchMemIds);
        }
        if ($roleId){
            $model->where('roleId',$roleId);
        }
        if ($nick){
            $model->where('nick','like',"%$nick%");
        }
        $paginate = $model->orderByDesc('id')->paginate($pageSize,'*','page',$page);
        $memberIds = collect($paginate->items())->pluck('memId')->unique()->toArray();
        $members = $this->userMemberService->getByIds($memberIds);
        foreach($paginate->items() as &$item){
            $memberId = $item['memId'] ?? null;
            $member = collect($members)->where('id',$memberId)->first();
            $item['memberName'] = data_get($member,'username');
            $item['logDate'] = date("Y-m-d H:i:s",$item['logTime']);
        }
        return $paginate;
    }
}
